﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
//
using PerceptiveMCAPI.Types.Internal;
//
namespace PerceptiveMCAPI.Types
{
   public class listInterestGroupingsOutput : Api_BaseOutput
   {
      public List<listInterestGroupingsResults> result { get; set; }
      public listInterestGroupingsParms inputParms { get; private set; }
      // --------------------------------------------------------
      public listInterestGroupingsOutput( listInterestGroupingsInput input )
         : base( input )
      {
         inputParms = input.parms;
         result = new List<listInterestGroupingsResults>();
      }
      // --------------------------------------------------- tostring
      public override string ToString()
      {
         return string.Format( "id: {0}, groupings: {1}", this.inputParms.id, "Not currently available" );
      }

      #region ================================================================== format setup

      // ---- serial
      internal void Format( string api_Request, string api_Response )
      {
         this.api_Request = api_Request;
         this.api_Response = api_Response;
         // ----------------------------------
         if ( this.api_OutputType == EnumValues.OutputType.JSON )
            outputJSON();
         else if ( this.api_OutputType == EnumValues.OutputType.XML )
            outputXML();
      }

      // ---- xmlrpc
      internal void Format( x_listInterestGroupings[] rpcResult )
      {
         this.api_Request = EnumValues.NotSupplied;
         this.api_Response = EnumValues.NotSupplied;
         // ------------------------
         this.result = FormatResults( rpcResult );
      }

      #endregion

      #region ================================================================= Output

      // ---------------------------------------------------------- outputXML
      private void outputXML()
      {
         XElement xml = XElement.Parse( this.api_Response );
         // error check
         Api_Error error = apiSerial.GetXmlOutputError( xml );
         if ( error != null )
         {
            this.api_ErrorMessages.Add( error );
            return;
         }
         // -------------------------------------------- get values
         try
         {
            int it;
            IEnumerable<XElement> groupings = xml.Elements( "struct" );
            List<listInterestGroupingsResults> results = new List<listInterestGroupingsResults>();
            foreach ( XElement xe_grouping in groupings )
            {
               listInterestGroupingsResults result = new listInterestGroupingsResults();
               int.TryParse( xe_grouping.Element( "id" ).Value, out it );
               result.grouping_id = it;
               result.name = xe_grouping.Element( "name" ).Value;
               result.form_field = apiHelper.GetEnumFromString<EnumValues.grouping_type_field>( xe_grouping.Element( "form_field" ).Value );
               int.TryParse( xe_grouping.Element( "display_order" ).Value, out it );
               result.display_order = it;
               if ( xe_grouping.Element( "groups" ).HasElements )
               {
                  IEnumerable<XElement> groups = xe_grouping.Element( "groups" ).Descendants( "struct" );
                  foreach ( XElement xe_group in groups )
                  {
                     listInterestGroupingsGroups group = new listInterestGroupingsGroups();
                     int.TryParse( xe_group.Element( "bit" ).Value, out it );
                     group.bit = it;
                     group.name = xe_group.Element( "name" ).Value;
                     int.TryParse( xe_group.Element( "display_order" ).Value, out it );
                     group.display_order = it;
                     int.TryParse( xe_group.Element( "subscribers" ).Value, out it );
                     group.subscribers = it;
                     result.groups.Add( group );
                  }
               }
               results.Add( result );
            }
            this.result = results;
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ---------------------------------------------------------- outputJSON
      private void outputJSON()
      {
         JavaScriptSerializer jss = new JavaScriptSerializer();

         try
         {
            if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
            {
               Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
               this.api_ErrorMessages.Add( err );
            }
            else
            {
               x_listInterestGroupings[] jsonResult = jss.Deserialize<x_listInterestGroupings[]>( this.api_Response );
               this.result = FormatResults( jsonResult );
            }
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ---------------------------------------------------------- FormatResults
      private List<listInterestGroupingsResults> FormatResults( x_listInterestGroupings[] results_array )
      {
         int it; long lng;
         List<listInterestGroupingsResults> results = new List<listInterestGroupingsResults>();
         //
         foreach ( x_listInterestGroupings entry in results_array )
         {
            listInterestGroupingsResults result = new listInterestGroupingsResults();
            result.grouping_id = entry.id;
            result.name = entry.name;
            result.form_field = apiHelper.GetEnumFromString<EnumValues.grouping_type_field>( entry.form_field );
            int.TryParse( entry.display_order, out it );
            result.display_order = it;

            foreach ( object item in entry.groups )
            {
               IDictionary dict = item as IDictionary;
               IDictionaryEnumerator de = dict.GetEnumerator();
               listInterestGroupingsGroups group = new listInterestGroupingsGroups();
               //
               long.TryParse( dict["bit"].ToString(), out lng );
               group.bit = lng;
               group.name = dict["name"].ToString();
               int.TryParse( dict["display_order"].ToString(), out it );
               group.display_order = it;
               int.TryParse( dict["subscribers"].ToString(), out it );
               group.subscribers = it;
               result.groups.Add( group );
            }
            results.Add( result );
         }
         return results;
      }

      #endregion
   }
}
